<template>
    <div class="container">
        <div class="handle-box">
                <el-form ref="form" :model="searchform" label-width="130px" class="flex">
                     <!-- <el-form-item label="负责区域：">
                        <el-input v-model="searchform.name" placeholder="请输入地区" class="handle-input mr10"  @input="mohu()"></el-input>
                    </el-form-item> -->
                    <el-form-item label="垃圾房名称：">
                        <el-input v-model="searchform.streetname" placeholder="请输入垃圾房名称" class="handle-input mr10" ></el-input>
                    </el-form-item>
                    <el-form-item class="flex">
                        <el-button type="primary" icon="el-icon-search" @click="mohu">搜索</el-button>
                        <!-- <el-button type="danger" icon="el-icon-circle-close">清空</el-button> -->
                        <!-- <el-button type="success" icon="el-icon-circle-plus-outline"  @click="handleAdd">新增</el-button>
                        <el-button style="padding:0;border:0">
                             <el-upload
                            action="/上传文件的接口"
                            :on-change="onChange"
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xls, .xlsx"  class="upload">
                        <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导入列表</el-button>
                       </el-upload>
                        </el-button>
                        <el-button type="primary" @click="exportToExcel()" style="background:#409EFF;border:1px solid #409EFF">导出列表</el-button> -->
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)">
            <!-- <el-table-column prop="BOX_ID" label="垃圾房ID"></el-table-column> -->
            <el-table-column prop="RUBBISHPOINTNAME" label="垃圾房名称"></el-table-column>
            <el-table-column prop="POINT" label="打分结果"></el-table-column>
            <el-table-column prop="WORKDATE" label="打分时间"></el-table-column>
            <el-table-column label="操作"  align="center" width="250">
              <template slot-scope="scope">
                <el-button type="text" @click="goDetailed(scope.$index, scope.row)"
                  >详细</el-button
                >
              </template>
            </el-table-column>

        </el-table>
        <div class="pagination">
            <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :current-page="currentPage"
                :page-size="pagesize"
                :total="tableData.length"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            ></el-pagination>
        </div>
    </div>
</template>
<script>
import '../../assets/css/common.css'
import OSS from 'ali-oss';
// import export2Excel from '@/utils/exportExcel/index.js'

export default {
    data(){
        return{
              currentPage:1, //初始页
                pageSize:10,    //    每页的数据      
                originalData: [],
                streetOpts: [],
                userList: [],
                address:'',
                name:'',
                value1: '',
                labelswidth: '160px',
                labelwidth: '120px',
                form:{
                    CLIENT_NO: '',
                    NAME: '',
                },
                optionstype:[{
                    typeID:1,
                    typeName: '巡查员'
                },{
                    typeID:2,
                    typeName: '巡查员'
                }],
                form:'',
                searchform : {
                name: '',
                streetname: '',
                communitname: ''
                },
            options: [],
            optionsstreet:[],
            optionscommunit:[],
            optionsplot: [],
            tableData: [
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addeditVisible:false,
            imgBroadcastList:[], // 储存旬中的图片列表
            imgsStr: '', // 后端需要的多张图base64字符串，分割
            dialogImageUrl: '',
            diaLogForm: {
              goodsName:'', // 商品名称字段
              imgBroadcastList:[], // 储存选中的图片列表
              imgsStr:''   // 后端需要的多张图base64字符串 , 分割
            },
            showBigDialogVisible: false,
            srcBig: '',
            //图片上传
            fileList: [],
            PicUrl: '', //存上传后的车辆副本照片url
            dataObj: {
              region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
              accessKeyId: 'LTAISI12uxTRFccz',
              accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
              bucket: 'photo-srw-hb2',
            }, //存签名信息
            baseAli: 'oss-cn-beijing.aliyuncs.com',
            rules: {
               CLIENT_NO: [
                 { required: true, message: '请选择巡查街道', trigger: 'change' }
               ],
               NAME: [
                 { required: true, message: '请填写姓名', trigger: 'change' }
               ],
             }
            }
            
       
    },
    created() {
        this.changeStreet();
        this.getdata();
        this.getselect()
    },
    methods: { 
    // 获取街道
    async changeStreet (val) {
            this.$axios({
                url: 'http://111.160.78.62:9943/GarbagePointsBDEApi/NewData/GetClientTreeApi?ClientNo=001',
                method: 'get',
            }).then(res=>{
                this.streetOpts = Object.assign([],res.data).filter(item => item.LEVEL === "3")
                console.log(this.streetOpts)
            })
    },
   // ----------以下为导入Excel数据功能--------------
   // 文件选择回调
   onChange(file, fileList) {
    //  console.log(fileList);
     this.fileData = file; // 保存当前选择文件
     this.readExcel(); // 调用读取数据的方法
   },
   // 读取数据
   readExcel(e) {
     let that = this;
     const files = that.fileData;
    //  console.log(files);
     if (!files) {
       //如果没有文件
       return false;
     } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
       this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
       return false;
     }
     const fileReader = new FileReader();
    //  console.log(fileReader)
     fileReader.onload = ev => {
       try {
         const data = ev.target.result;
        //  console.log(ev.target)
        //  console.log(this);
         const workbook = this.XLSX.read(data, {
           type: "binary"
         });
         const wsname = workbook.SheetNames[0]; //取第一张表
         const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          let exceldata =  [] 
         ws.filter(item=>{
             var sheetData = {
              NAME: item["巡查员姓名"],
              CLIENT_NO: item["巡查街道"],
              WORKTYPE: "巡查员",
              SIMCARD_NO: item['设备号'],
              BOX_ID: item['垃圾房ID'],
              PHONE: item['手机号'],
              IDCARD: item["身份证号码"],
              CHECKCODE: item["登录密码"],
              WECHAT: item["微信号"],
              REMARK: item["备注"],
              PHOTO: "",
           }
             console.log(sheetData);
             exceldata.push(sheetData)
         })
         console.log(exceldata)
        this.$axios({
          url: 'http://111.160.78.62:9943/GarbagePointsBDEApiGarbagePointsBDEApi/NewData/AddWorkerApi',
          method: 'post',
          data: exceldata
        }).then(res=>{
          console.log(res)
          if(res.data.IsSucess){
            this.$message.success('导入成功')
            this.getdata()
          }
        })
         this.$refs.upload.value = "";
       } catch (e) {
         return false;
       }
     };
     // 如果为原生 input 则应是 files[0]
     fileReader.readAsBinaryString(files.raw);
   },
        async getdata(){
        var url = 'http://111.160.78.62:9943/GarbagePointsBDEApi/BasicData/GetRubbishPointForAccess' 
            //var url = this.$url + '/GetCollectorListApi?CLIENT_NO=' + localStorage.getItem('clentno')
            const { data } = await this.$axios.get(url)
            this.originalData = data
            this.screeningData()
        },
         async getselect(){
            const { data } = await this.$axios.get(this.$url+'/GetRegionListApi')
            this.options = data.filter(item => {
              return item
            })
        },
        async changevalue(e){
            const { data } =await this.$axios.get(this.$url+'/sreetListsApi?id='+e);
            this.optionsstreet = data.filter(item => {
                return item 
            })

        },
        async changecommunitvalue(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/communityListsApi?id='+e);
            this.optionscommunit = data.filter(item => {
                // console.log(item)
                return item 
            })

        },
        async changeplot(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/villageListsApi?id='+e);
            this.optionsplot = data.filter(item => {
                // console.log(item)
                return item 
            })
        },
        // 模糊查询
        screeningData () {
          this.currentPage = 1
          this.tableData = this.originalData
          if (this.searchform.streetname) this.tableData = this.tableData.filter(item => item.RUBBISHPOINTNAME.includes(this.searchform.streetname))
        },
        // 导出功能
        exportToExcel(){
            require.ensure([],()=>{
              const {export_json_to_excel} = require('../../excel/export2Excel');
              const tHeader = ['巡查员姓名','巡查街道', '人员类型','设备号','垃圾房ID','手机号','身份证号码','登陆密码','微信号','备注'];
              const filterVal = ['NAME','CLIENT_NO', 'WORKTYPE','SIMCARD_NO','BOX_ID','PHONE','IDCARD','PWD','WECHAT','REMARK'];
              const list = this.tableData;
              const data = this.formatJson(filterVal, list);
              console.log(data)
              export_json_to_excel(tHeader, data, "巡查员信息表");
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        addlistdatadiglog(){
            this.addeditVisible = true
        },
        addsaveEdit(form){
            console.log(this.form);
            this.$axios({
                // url:this.$url + '/AddCollectorlApi',
                url: 'http://111.160.78.62:9943/GarbagePointsBDEApiGarbagePointsBDEApi/NewData/AddWorkerApi',
                // url:'http://192.168.1.113:6607/GarbagePointsTYApi/BasicData/AddCollectorlApi',
                method: 'post',
                data:{
                    NAME: this.form.NAME,
                    WORKTYPE:"巡查员",
                    SIMCARD_NO: this.form.SIMCARD_NO,
                    BOX_ID: 0,
                    CLIENT_NO: this.form.CLIENT_NO,
                    PHONE: this.form.PHONE,
                    IDCARD: this.form.IDCARD,
                    WECHAT: this.form.WECHAT,
                    PWD: this.form.PWD,
                    REMARK: this.form.REMARK,
                    PHOTO: this.PicUrl,
                }
            }).then((res)=>{
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('新增成功');
                    this.getdata()
                }
            })
            this.addeditVisible =false
        },
         mohu() {
            var search = this.searchform.name;
            console.log(search)
            var newdate = [];
            if(search){
                if(search)
                 this.tableData.filter(item=>{
                     console.log(item)
                    if(item.name.indexOf(search) != -1){
                        newdate.push(item)
                    }
                })
            }else if (search == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        
        // 打开新增窗口
        handleAdd () {
          //清空编辑框
          this.form = {}
          this.addDialogTitle = '新增巡查员信息'
          //展示窗口
          this.addeditVisible = true;
        },
        // 编辑操作
        handleEdit(index, row) {
            this.form = Object.assign({}, row);
            this.addDialogTitle = '编辑巡查员信息'
            this.addeditVisible = true;
        },
        // 点击保存，判断是新增还是编辑操作
        handleSubmit (formName) {
        // 必填规则
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.addDialogTitle == '新增巡查员信息') {
              this.addsaveEdit()
            } else {
              this.saveEdit()
            }
          } else {
            console.log('error submit!!');
            return false;
          }
          });
          
        },
        //删除操作
        handleDelete(index, row) {
            this.$confirm('确定删除？', '提示', {
                type: 'warning'
            }).then(res=>{
                var aa = {
                    VID: row.VID,
                }
                this.$axios({
                url: 'http://111.160.78.62:9943/GarbagePointsBDEApiGarbagePointsBDEApi/NewData/DeleteWorkerApi',
                method:'post',
                data: aa
                }).then(res=>{
                    this.$message.success('删除成功')
                    this.getdata()
                })
                
            })
            
        },
        // 放大图片
        bigImage (row) {
          this.srcBig = row.PHOTO
          this.showBigDialogVisible = true
        },
        handleClose () {
          this.showBigDialogVisible = false;
        },
        // 点击上传巡查员图片按钮
        clickBYFJPic () {
          this.$refs.XCYPicFile.click();
        },
        changeBYFJPic () {
          this.afterRead(this.$refs.XCYPicFile.files[0]);
          this.$refs.XCYPicFile.value = null; // 移除文件，可以保证上传同样的文件时，也会触发change事件
        },
        afterRead (file) {
          return new Promise((resolve, reject) => {
            // 此时可以自行将文件上传至服务器
            const that = this
            let client = new OSS(this.dataObj)
            const fileName = file.name
            //定义唯一的文件名，打印出来的uid其实就是时间戳
            //client 是第一步中的 client
            client
              .multipartUpload(fileName, file)
              .then((result) => {
                //下面是如果对返回结果再进行处理，根据项目需要
                // console.log(result)
                that.PicUrl =
                  'http://' +
                  result.bucket +
                  '.' +
                  that.baseAli +
                  '/' +
                  result.name
                console.log(that.tempUrl)
                resolve()
              })
              .catch((err) => {
                console.log('err:', err)
                reject()
              })
          })
        },
        handleAvatarSuccess (res, file) {
          this.imageUrl = URL.createObjectURL(file.raw)
        },
        // 保存编辑
        saveEdit() {
            let PATH = ''
            if (this.PicUrl === '') {
              //未做选择修改
              PATH = this.form.PHOTO
            } else {
              PATH = this.PicUrl
            }
            var aa = {
                    VID:this.form.VID,
                    NAME: this.form.NAME,
                    WORKTYPE:"巡查员",
                    SIMCARD_NO: this.form.SIMCARD_NO,
                    BOX_ID: this.form.BOX_ID,
                    CLIENT_NO: this.form.CLIENT_NO,
                    PHONE: this.form.PHONE,
                    IDCARD: this.form.IDCARD,
                    WECHAT: this.form.WECHAT,
                    PWD: this.form.PWD,
                    REMARK: this.form.REMARK,
                    CHECKCODE:"",
                    PHOTO: PATH,
                    CHECKTIME: "",
                    ISUSE: "True",
                }
            this.$axios({
                // url: this.$url + '/UpdateCollectorApi',
                url: 'http://111.160.78.62:9943/GarbagePointsBDEApiGarbagePointsBDEApi/NewData/UpdateWorkerApi',
                method: 'post',
                data: aa
            }).then(res=>{
                console.log(res.data)
                if(res.data.IsSucess){
                    this.$message.success('编辑成功')
                    this.editVisible = false
                    this.getdata()
                }else{
                    this.$message.err('编辑失败')
                }
            })
            // this.editVisible = false;
        },
        // 分页导航
        handlePageChange(currentPage) {
            this.currentPage = currentPage;
            console.log(this.currentPage)
            // this.$set(this.query, 'pageIndex', val);
            // this.getData();
        },
        handleSizeChange(size){
            this.pageSize = size;
            console.log(this.pageSize)
        },
        routerhandleEdit(){
            this.$router.push('/plotintegral')
        },
        goDetailed(index, row){
          // 进入视频监控页面
          this.$router.push({ path: '/QueryWorkFeedback', query: { VID: row.BOX_ID,TIME: row.WORKDATE } })
        }
    }
}
</script>
<style scoped>
    .el-select{
        width: 100%;
    }
    /deep/.el-upload__input{
    display: none!important;
}
/deep/.el-upload__input{
    display: none;
}
/deep/.el-form-item__content{
    display: flex;
}
</style>